<script setup lang="ts">
import { reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useArticlesStore } from '@/stores/articles'
import { useUserStore } from '@/stores/user'
import { usePerm } from '@/composables/perm'

const route = useRoute()
const router = useRouter()
const form = reactive({ id: 0, title: '', content: '', status: 'draft' as 'draft' | 'published' })
const store = useArticlesStore()
const user = useUserStore()
const perm = usePerm()

onMounted(() => {
  if (!store.items.length) store.hydrate()
  const id = Number(route.params.id)
  if (id) {
    const item = store.items.find(i => i.id === id)
    if (item) {
      if (!perm.canEditArticle(item.author)) {
        router.replace('/articles')
        return
      }
      form.id = id
      form.title = item.title
      form.content = `文章 #${id} 的内容...`
      form.status = item.status
    }
  }
})

const save = () => {
  if (form.id) {
    const item = store.items.find(i => i.id === form.id)
    if (!item) return
    if (!perm.canEditArticle(item.author)) return
    store.update(form.id, { title: form.title, status: form.status })
  } else {
    store.create({ title: form.title, author: user.name || 'Unknown', status: form.status })
  }
  router.replace('/articles')
}
</script>

<template>
  <div style="padding:16px">
    <el-card>
      <el-form label-width="80px" style="max-width:720px">
        <el-form-item label="标题">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" style="width:200px">
            <el-option label="草稿" value="draft" />
            <el-option label="已发布" value="published" />
          </el-select>
        </el-form-item>
        <el-form-item label="内容">
          <el-input type="textarea" rows="10" v-model="form.content" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="save">保存</el-button>
          <el-button @click="router.back()">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
  
</template>

<style scoped>
</style>


